package top.jle.wx.proxy.api;



import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

import io.swagger.v3.oas.annotations.Hidden;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RestController;
import top.jle.jpa.basic.exception.BasicCustomException;
import top.jle.jpa.basic.exception.BasicExceptionCode;
import top.jle.jpa.basic.log.BussLog;

import java.util.Map;

@RestController
@Hidden
@EnableConfigurationProperties({ServerProperties.class})
public class APIErrorHandler extends BasicErrorController {

    /**
     * 必须实现的一个构造方法
     **/
    public APIErrorHandler() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }


    @Override
    @BussLog
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request){
        Map<String, Object> body = getErrorAttributes(request, ErrorAttributeOptions.of(ErrorAttributeOptions.Include.EXCEPTION, ErrorAttributeOptions.Include.MESSAGE));
        HttpStatus status = getStatus(request);
        ResponseBack<String> back =  ResponseBack.error(new Exception());
        back.setCode(body.get("status").toString());
        back.setResult(null);
        back.setResult(body.containsKey("message")?body.get("message").toString():body.get("error").toString());
        if(body.containsKey("exception")){
            String exception =  body.get("exception").toString();
            if(exception.equals(BasicCustomException.class.getName())){
                JSONObject exceptionInfo = JSONObject.parseObject(body.get("message").toString());
                back.setCode(exceptionInfo.getString("code"));
                back.setResult(exceptionInfo.getString("message"));
            }else{
                back.setCode(BasicExceptionCode.SERVER_ERROR.getCode());
            }
            back.setResult(null);
        }
        return new ResponseEntity<>((JSONObject) JSON.toJSON(back), status);
    }




}
